import axios from "axios";
import { Notify,Toast } from "vant";
// import router from "../router.js";
import {native} from '../views/app.js';
const cachios = require('cachios');


const Axios = axios.create({
    baseURL: process.env.VUE_APP_MOCK_URL,
    timeout: 40000,
    responseType: "json",
    withCredentials: false, // 不需要cookie
});

const cachiosInstance = cachios.create(Axios, {
    stdTTL: 2,
});
Axios.interceptors.request.use(
    config => {
        if (sessionStorage.getItem('token')) {
            config.headers.Authorization = 'Bearer ' + sessionStorage.getItem('token');
            config.headers.city = sessionStorage.getItem('cityId');
        }
        return config;
    },
    error => {
        Notify({
            message: error,
            duration:1000,
            background: "#f44"
        });
        return Promise.reject(error.data.error.message);
    }
);
Axios.interceptors.response.use(
    res => {
        return res;
    },
    error => {
        if (error.message && (error.message.indexOf('timeout') > -1)) {
            Notify({
                message: '网络请求超时',
                duration: 1000,
                background: "#f44"
            });
            return Promise.reject(error);
        }
        if (error.response) {
            Notify({
                message: error.response.data.msg || '网络错误',
                duration:1500,
                background: "#f44"
            });
            if (error.response.status === 401) {
                try {
                    native.logout();
                } catch (e) {
                    window.location.href = window.location.origin + '/#/login/index';
                }
            }
            // if (error.response.status === 412) {
            //     Toast.fail(error.response.data.msg);
            // }

        }
        // let errorInfo =  error.data.error ? error.data.error.message : error.data;
        // let errorInfo =  error.response.data;
        // return Promise.reject(errorInfo);
        return Promise.reject(error);
    }
);
export default {
    install: function (Vue) {
        Object.defineProperty(Vue.prototype, "$http", {value: cachiosInstance});
    }
};
